package com.ja.openchat.ui.me;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.JsonObject;
import com.ja.openchat.R;
import com.ja.openchat.ui.chat.ChatActivity;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.group.SuperGroupInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.util.DensityUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PublicGroupFragment extends AbsListFragment<ChatInfo,PublicGroupAdapter> {

    @Override
    protected void initDataAndEvent(Bundle savedInstanceState) {
        super.initDataAndEvent(savedInstanceState);
        recyclerView.setClipToPadding(false);
        recyclerView.setPadding(0, DensityUtil.dip2px(10),0,DensityUtil.dip2px(10));
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                ChatInfo chatInfo = mAdapter.getItem(position);
                if(chatInfo!=null){
                    ChatActivity.startActivity(getContext(),chatInfo);
                }
            }
        });
        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                ChatInfo chatInfo = mAdapter.getItem(position);
                if(chatInfo!=null){
                    SuperGroupInfo superGroupInfo = mAdapter.getSuperGroupInfo(chatInfo);
                    if(superGroupInfo!=null&&superGroupInfo.status!=null&&superGroupInfo.status.isMyGroup()){
                        ChatActivity.startActivity(getContext(),chatInfo);
                    }else{
                        showProgress();
                        TelegramManager.getTelegramManager().joinChat(getContext(), chatInfo.id, new TgResultBlock<TgResponse>() {
                            @Override
                            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                                hideProgress();
//                                ChatActivity.startActivity(getContext(),chatInfo);

                            }

                            @Override
                            public void onTimeout(Map<String, Object> request) {
                                hideProgress();
                                ToastUtils.showShort(getString(R.string.failed_to_join_group));
                            }
                        });
                    }

                }
            }
        });
    }

    @Override
    protected PublicGroupAdapter newIntanceAdapter() {
        return new PublicGroupAdapter();
    }


    @Override
    protected void requestData(int page) {
        TelegramManager.getTelegramManager().searchPublicChats(getContext(), (page-1)*PAGE_COUNT,PAGE_COUNT,new TgResultBlock<List<Long>>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, List<Long> obj) {
                initSearchResult(page,obj);
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                finishRefreshAndLoad(page,null);
            }
        });
    }

    private void initSearchResult(int page,List<Long> chatIds){
        if (chatIds != null && chatIds.size() > 0) {
            HashMap<Long,ChatInfo> hashMap = new HashMap<>();
            for (long chatId : chatIds) {
                TelegramManager.getTelegramManager().requestChatInfoByChatId(getContext(), chatId, new TgResultBlock<ChatInfo>() {
                    @Override
                    public void onResult(Map<String, Object> request, JsonObject response, ChatInfo obj) {
                        hashMap.put(chatId,obj);
                        if(hashMap.size()==chatIds.size()){
                            reloadListUI(page,hashMap);
                        }
                    }

                    @Override
                    public void onTimeout(Map<String, Object> request) {

                    }
                });
            }
        }else{
            reloadListUI(page,null);
        }
    }

    private void reloadListUI(int page,HashMap<Long,ChatInfo> hashMap){
        List<ChatInfo> chatInfos = new ArrayList<>();
        if(hashMap!=null&&hashMap.size()>0){
            for (Long o : hashMap.keySet()) {
                ChatInfo fullInfo = hashMap.get(o);
                if(fullInfo.isSuperGroup()){
                    chatInfos.add(fullInfo);
                }
            }
        }
        finishRefreshAndLoad(page,chatInfos);
    }

    @Override
    protected boolean isHaveEventBus() {
        return true;
    }

    @Override
    public void onTgEvent(TgEvent tg_event) {
        switch (tg_event.event){
            case EUser_Td_Group_Super_Info_Changed:
                if(tg_event.data!=null&&tg_event.data instanceof SuperGroupInfo){
                    SuperGroupInfo superGroupInfo = (SuperGroupInfo) tg_event.data;
                    mAdapter.updateMeGroupStatus(superGroupInfo,true);
                }
                break;
        }

    }
}
